package com.tuanzi.loan.web.bean.businesssystem;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.entity.businesssystem.BusinessMain;
import com.tuanzi.loan.business.service.businesssystem.BusinessMainService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.web.configuration.JSFInfoBean;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.util.List;

import static com.tuanzi.loan.business.constants.DictionaryCode.BUSINESS_MAIN_TYPE;
import static com.tuanzi.loan.business.constants.DictionaryCode.SETTLEMENT_PAY_MODE;

@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class BusinessMainInfoBean extends JSFInfoBean<BusinessMain> {
    @Autowired
    private BusinessMainService settlementCompanyService;
    @PostConstruct
    private void init() {
        //生效时间设置
        String id = getParamFromRequest("id");
        if (StringUtils.isNotBlank(id)) {
            $ = settlementCompanyService.findOne(Long.parseLong(id));
        } else {
            $ = new BusinessMain();
            changeStatusToAdd();
        }
    }

    public String onSave(){
        if (validate() == false) return null;
        if ($.getId() == null){//新增公司时，默认公司的预付金额为0，消耗金额为0
            $.setPrepayAmount(0.0);
            $.setExpendAmount(0.0);
            $.setBillAmount(0.0);
        }
        if ($.getPayType()==null){
            $.setPayType(0);
        }
        $ = settlementCompanyService.saveOrUpdate($);
        changeStatusToView();
        addSuccessfullyMessage();
        return redirect("/views/businesssystem/main-list.xhtml");
    }

    public boolean validate(){
            if ($.getChannelMain() == null){
                addErrorMessage("渠道主体为空");
                return false;
            }
        if ($.getMainType() == null){
            addErrorMessage("主体类型为空");
            return false;
        }
        return true;
    }


    @Override
    protected List<String> getDictionaryCodes() {
        return  Lists.newArrayList(BUSINESS_MAIN_TYPE,SETTLEMENT_PAY_MODE);
    }
}
